package org.adorsys.aderp.aderplogin.web.ext;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.adorsys.aderp.aderplogin.client.ClientDetailsHelper;
import org.adorsys.aderp.aderplogin.domain.AderpClientDetail;
import org.adorsys.aderp.aderplogin.domain.AderpUser;
import org.adorsys.aderp.aderplogin.domain.UserRole;
import org.adorsys.aderp.aderplogin.service.AderpClientDetailService;
import org.adorsys.aderp.aderplogin.service.AderpUserService;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
public class WorkspaceService {

	@Resource
	private AderpClientDetailService aderpClientDetailService;
	
	@Resource
	private AderpUserService aderpUserService;
	
	public List<Workspace> selectWorkspaces(){
		List<Workspace> result = new ArrayList<Workspace>();
		UserDetails userDetails = SecurityUtils.getUserDetails();
		if(userDetails==null) return Collections.emptyList();
		
		AderpUser aderpUser = aderpUserService.findByUserName(userDetails.getUsername());
		List<AderpClientDetail> clientDetails = aderpClientDetailService.findAllAderpClientDetails();
		for (AderpClientDetail aderpClientDetail : clientDetails) {
			if("aderp-login".equals(aderpClientDetail.getClientId())) continue;
			Set<UserRole> supportedRoles = ClientDetailsHelper.getSupportedRoles(aderpUser, aderpClientDetail);
			for (UserRole userRole : supportedRoles) {
				Workspace workspace = new Workspace();
				workspace.setBaseUrl(aderpClientDetail.getRegisteredRedirectUri());
				workspace.setWorkspaceName(userRole.getTitle());
				workspace.setRoleKey(userRole.getRoleKey());
				result.add(workspace);
			}
		}

		return result;
	}
	
}
